# -*- coding:utf-8 -*-
# Author:lixuecheng
from flask import Flask
import socket
import threading
import os
import time
socket.setdefaulttimeout(3)


def socket_port(ip, port):
    """
    输入IP和端口号，扫描判断端口是否占用
    """
    try:
        if port >= 65535:
            return False, '端口过大'
        s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
        result = s.connect_ex((ip, port))
        if result == 0:
            return False, '已占用'
        else:
            return True, ''
    except Exception as e:
        return False, str(e)

class DoWeb:
    def __init__(self, port=None, is_debug=False):
        if port is None:
            self.port = 10000
            while self.port < 65535:

                c, _ = socket_port('0.0.0.0', self.port)
                if c:
                    break
                else:
                    self.port += 1
            else:
                raise Exception('当前无端口可用')
        else:
            c, v = socket_port('0.0.0.0', int(port))
            if c:
                self.port = int(port)
            else:
                raise Exception(v)
        self.pid=os.getpid()
        self.app = Flask('WebApp_'+str(self.pid),static_url_path='')
        if is_debug:
            self.app.debug = True
        self.endport_index = 0
        

    def add_route(self, rule, func, methods=['get']):
        self.endport_index += 1
        self.app.add_url_rule(str(rule), methods=methods,
                              view_func=func, endpoint=str(self.endport_index))
        
    def add_static_file(self,rule):
        self.endport_index += 1
        app=self.app
        f_n=''
        if rule.startswith('/'):
            f_n=rule[1:]
        else:
            f_n=rule

        def f():
            return app.send_static_file(f_n)
        # print(__file__,__package__)
        p=os.path.join(os.path.dirname(os.path.dirname(__file__)),'static')
        file=os.path.join(p,f_n)
        if not os.path.exists(file):
            print('[warn] {} 目录下没有文件：{}'.format(p,f_n))
        
        self.app.add_url_rule(str(os.path.dirname(rule)), methods=['get'],
                              view_func=f, endpoint=str(self.endport_index))

    def start(self):
   
        self.add_route('/close_'+str(self.pid),self.close)
        print('close with http://localhost:'+str(self.port)+'/close_'+str(self.pid))
        # threading.Thread(target=self.app.run,kwargs={'host':'0.0.0.0','port':int(self.port)}).start()
        self.app.run(host='0.0.0.0', port=int(self.port))

      

    def close(self):
        a=os.popen('taskkill /pid {} /f'.format(str(self.pid)))
        b=a.read()
        print(b)
        return  b
        

        # self.app.run(host='0.0.0.0', port=int(self.port))


# def hi(name):
#     return name


d = DoWeb()
d.add_static_file('/1.html')
d.add_static_file('/js/2.html')

# d.add_route('/test/<name>', hi)
d.start()
# time.sleep(5)
# d.close()
# app.add_url_rule('/', methods=['post','get'], view_func=hi)

# if __name__ == '__main__':
#     app.debug=True
#     app.run(host="0.0.0.0", port=8081)
